package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSONObject;
import com.ys.entity.eKnowAi.*;
import com.ys.entity.sys.YsCol;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.service.eKnowAi.EKnowChatLogManageService;
import com.ys.service.eKnowAi.EKnowChatLogService;
import com.ys.service.eKnowAi.EKnowKnowledgeListService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/eKnowChatLogManage")
public class ApiInterEKnowChatLogManageController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterEKnowChatLogManageController.class);
    private static Long MENU_ID = 136L;

    @Autowired
    private CommonApiService<EKnowChatLogManage> commonApiService;

    @Autowired
    private EKnowChatLogService eKnowChatLogService;

    @Autowired
    private EKnowChatLogManageService eKnowChatLogManageService;
    @Autowired
    private EKnowKnowledgeListService eKnowKnowledgeListService;


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public EKnowChatLogManage setSeachSql(EKnowChatLogManage cond){
        cond.addField("A.UserId + '/' + U.UserName AS userName");//提问人
        cond.addField("T.TypeName AS typeName");//分类名称
        cond.addField("B.KnowledgeBaseName AS knowledgeBaseName");//知识库名称
        cond.addField("CASE WHEN A.IsSaveKnowledge = 0 THEN '否' WHEN A.IsSaveKnowledge = 1 THEN '是' ELSE '未记录' END isSaveKnowledgeTxt ");//是否已存入知识库（0否，1是）
        cond.addLeftJoin("kjecp.dbo.TS_UserInfo U ON U.UserId = A.UserId");
        cond.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeType T ON T.Id = A.KnowledgeTypeId AND A.IsSaveKnowledge = 1");
        cond.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase B ON B.Id = T.BaseId  AND B.Id IS NOT NULL");
        //排序
        cond.setOrderby("A.UpdateTime DESC");
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("eKnowChatLogManage:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute EKnowChatLogManage cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询日志管理出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute EKnowChatLogManage cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENU_ID)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<EKnowChatLogManage> util = new ExportExcelUtils<>(new EKnowChatLogManage());
            String toFilePath = util.exportExcel(listData, listField, "逸知道Ai日志管理");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出逸知道Ai日志管理出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 批量删除日志管理
     */
    @PostMapping("/delChatLogManageByBatch")
    @ResponseBody
    public JSONObject delChatLogManageByBatch(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            int isDels = 0;
            for(String item:idArr){
                long id = Long.parseLong(item);//Id
                int isDel = eKnowChatLogManageService.del(id);
                if(isDel>0){
                    isDels++;
                }
            }
            if(isDels>0){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("逸知道批量删除日志管理信息出错：",e.getMessage(),e);
        }
        return result;
    }

    /**
     * 批量上传知识库
     */
    @PostMapping("/uploadChatLogManageToKnowledge")
    @ResponseBody
    public JSONObject uploadChatLogManageToKnowledge(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            long baseId = Long.parseLong(params.get("baseId").toString());//知识库Id
            long typeId = Long.parseLong(params.get("typeId").toString());//所属分类id
            String isRemoveBlank = params.get("isRemoveBlank").toString();//是否去除连续的空格与换行，0否1是
            String idstr = params.get("ids").toString();
            String[] ids = idstr.split(",");
            int isUploads = 0;
            EKnowKnowledgeBase eKnowKnowledgeBase = new EKnowKnowledgeBase().setId(baseId).queryFirst();
            if(eKnowKnowledgeBase!=null) {
                String indexName = eKnowKnowledgeBase.getESIndexName();//索引名称
                for(String id:ids){
                    EKnowChatLogManage eKnowChatLogManage = new EKnowChatLogManage().setId(Long.parseLong(id)).queryFirst();
                    if(eKnowChatLogManage!=null){
                        Map<String, Object> paramsNew = new HashMap<>();
                        paramsNew.put("baseId",baseId);
                        paramsNew.put("typeId",typeId);
                        paramsNew.put("isRemoveBlank",isRemoveBlank);
                        paramsNew.put("information",eKnowChatLogManage.getContent());
                        int isUpload = eKnowKnowledgeListService.addKnowledgeListByList(paramsNew,indexName);
                        if(isUpload>0){
                            EKnowChatLogManage eKnowChatLogManageUpdate = new EKnowChatLogManage();
                            eKnowChatLogManageUpdate.setIsSaveKnowledge(1);
                            eKnowChatLogManageUpdate.setKnowledgeTypeId(typeId);
                            eKnowChatLogManageUpdate.setId(Long.parseLong(id));
                            int isSave = eKnowChatLogManageService.update(eKnowChatLogManageUpdate);
                            isUploads++;
                        }
                    }
                }
            }
            if(isUploads>0){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("逸知道批量上传知识库出错：",e.getMessage(),e);
        }
        return result;
    }

    /**
     * 查看详情
     */
    @PostMapping("/eKnowChatLogManageDetail")
    @ResponseBody
    public JSONObject eKnowChatLogManageDetail(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            long id = Long.parseLong(params.get("id").toString());//id

            EKnowChatLogManage eKnowChatLogManage = new EKnowChatLogManage().setId(id).queryFirst();
            if(eKnowChatLogManage!=null){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
                result.put("eKnowChatLogManage", eKnowChatLogManage);
                EKnowChatLog eKnowChatLog = new EKnowChatLog().setId(eKnowChatLogManage.getOldLogId()).queryFirst();
                if(eKnowChatLog!=null){
                    result.put("eKnowChatLog", eKnowChatLog);
                }
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("逸知道日志管理查看详情出错：",e.getMessage(),e);
        }
        return result;
    }



    /**
     * 修改
     */
    @PostMapping("/eKnowChatLogManageUpdate")
    @ResponseBody
    public JSONObject eKnowChatLogManageUpdate(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            long id = Long.parseLong(params.get("id").toString());//id
            String content = params.get("content").toString();
            EKnowChatLogManage eKnowChatLogManage = new EKnowChatLogManage();
            eKnowChatLogManage.setContent(content);
            eKnowChatLogManage.setId(id);
            int isSave = eKnowChatLogManageService.update(eKnowChatLogManage);
            if(isSave>0){
                result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            }else {
                result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            }
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("逸知道日志管理修改出错：",e.getMessage(),e);
        }
        return result;
    }


    /**
     *	查询知识库分类、名称信息
     */
    @PostMapping("/searchEKnowLedgeBaseInfo")
    @ResponseBody
    public JSONObject searchEKnowLedgeBaseInfo(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        JSONObject result = new JSONObject();
        try {
            List<EKnowKnowledgeType> eKnowKnowledgeTypeList = new EKnowKnowledgeType().setOrderby("A.Sort ASC").queryList();
            List<EKnowKnowledgeBase> eKnowKnowledgeBaseList = new EKnowKnowledgeBase().setOrderby("A.Sort ASC").queryList();
            result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
            result.put("eKnowKnowledgeTypeList", eKnowKnowledgeTypeList);
            result.put("eKnowKnowledgeBaseList", eKnowKnowledgeBaseList);
        }catch (Exception e) {
            result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
            logger.error("查询知识库分类、名称信息出错：",e.getMessage(),e);
        }
        return result;
    }





}